package cn.hxzy.zyicon.service.impl;

import cn.hxzy.zyicon.entity.User;
import cn.hxzy.zyicon.entity.vo.PageBean;
import cn.hxzy.zyicon.repository.UserRepository;
import cn.hxzy.zyicon.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public PageBean<User> findAll(PageBean<User> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<User> all = userRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return pageBean;
    }


    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public void delete(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public void update(User user) {
        userRepository.save(user);
    }


    @Override
    public User findById(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public User findByLoginNameAndLoginPassword(String loginName, String loginPassword) {
        Optional<User> byLoginName = userRepository.findByLoginName(loginName);
        if (byLoginName.isPresent()) {
            User user = byLoginName.get();
            if (user.getLoginPassword().equals(loginPassword)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public PageBean<User> findUserByNameLike(String name, PageBean<User> userPageBean) {
        name="%"+name+"%";
        Pageable pageable = PageRequest.of(userPageBean.getPage() - 1, userPageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<User> all= userRepository.findUserByNameLike(pageable,name);
        userPageBean.setList(all.getContent());
        userPageBean.setCount(all.getTotalElements());
        userPageBean.setPageCount(all.getTotalPages());
        return userPageBean;

    }



}

